package com.uuah.server.transport.provider.mina.codecs.server;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.uuah.server.UuahServer;
import com.uuah.server.api.message.IUuahBusiMessageCollection;
import com.uuah.server.util.UuahBusiMessageUtils;

public class UuahRequestMessageDecoder extends CumulativeProtocolDecoder {
	protected transient Logger logger = LoggerFactory.getLogger(getClass());
	protected CharsetDecoder decoder;

	public UuahRequestMessageDecoder() {
		decoder = Charset.forName(
				UuahServer.getUuahContext().getConfiguration()
						.getDefaultEncoding()).newDecoder();
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		IUuahBusiMessageCollection uuahBusiMessageCollection = UuahBusiMessageUtils
				.getValidUuahBusiMessageCollection(in, decoder);
		if (logger.isDebugEnabled()) {
			logger.debug("uuahBusiMessage decode finished!Message Count:"
					+ uuahBusiMessageCollection.size());
		}
		if (uuahBusiMessageCollection.size() == 0) {
			return false;
		} else {
			out.write(uuahBusiMessageCollection);
			return true;
		}
	}
}
